const multer = require("multer")
const cors = require("cors")
const express = require("express")
const ffmpeg = require('fluent-ffmpeg');
const fs = require("fs")
const path = require("path")
const pathToFfmpeg = require('ffmpeg-static')
ffmpeg.setFfmpegPath(pathToFfmpeg);
console.log(pathToFfmpeg);
const storage = multer.diskStorage({
    destination: 'tem_upload/',
    filename: (req, file, cb) => {
        cb(null, `${req.body.index}-${req.body.fileName}`)
    }
})
const upload = multer({ storage })
const app = express()

app.use(cors())
app.use(express.json())

app.post('/partUpload', upload.single('file'), (req, res) => {
    res.send('ok')
})
app.post("/merge", (req, res) => {
    // 读取目录所有切片
    const uploadDir = path.join(process.cwd(), 'tem_upload') //process.cwd当前目录
    const dirs = fs.readdirSync(uploadDir)
    dirs.sort((a, b) => {
        return a.split('-')[0] - b.split('-')[0]
    })
    const filePath = path.join(process.cwd(), "file", req.body.fileName)
    dirs.forEach(item => {
        fs.appendFileSync(filePath, fs.readFileSync(path.join(uploadDir, item)))
        fs.unlinkSync(path.join(uploadDir, item))
    })
    res.send('ok');
})
app.get("/", (req, res) => {
    res.send("Nih ")
})
app.post("/transcode", (req, res) => {
    const { videoUrl } = req.body;
    res.setHeader('Content-Type', 'video/mp4');
    ffmpeg(videoUrl)
        .format('mp4').videoCodec('libx264')
        .on('start', () => {
            console.log('ffmpeg process started for URL: ' + videoUrl);
        }).on("progress",dd=>{
            console.log("//",dd);
        })
        .on('end', () => {
            console.log('ffmpeg process finished.');
            const stream = fs.createReadStream("./file_handler/test.mp4")
            stream.pipe(res)
        }).on('error', (err) => {
            console.error('Error: ' + err.message);
            res.status(500).send('Internal Server Error');
        }).save("./file_handler/test.mp4")

})
app.listen(9999, () => {
    console.log('Server is running on port 9999')
})

